package com.ruoyi.miniapp.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.miniapp.MiniAppUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.map.SoMap;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.miniapp.domain.TMiniHistory;
import com.ruoyi.miniapp.mapper.MiniAppUserMapper;
import com.ruoyi.miniapp.mapper.TMiniHistoryMapper;
import com.ruoyi.miniapp.service.ITMiniHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 体重监测历史数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-06-11
 */
@Service
public class TMiniHistoryServiceImpl extends ServiceImpl<TMiniHistoryMapper, TMiniHistory> implements ITMiniHistoryService
{
    @Autowired
    private TMiniHistoryMapper tMiniHistoryMapper;

    @Autowired
    private MiniAppUserMapper miniAppUserMapper;

    /**
     * 查询体重监测历史数据
     *
     * @param id 体重监测历史数据主键
     * @return 体重监测历史数据
     */
    @Override
    public TMiniHistory selectTMiniHistoryById(String id)
    {
        return tMiniHistoryMapper.selectTMiniHistoryById(id);
    }

    /**
     * 查询体重监测历史数据列表
     *
     * @param params 体重监测历史数据
     * @return 体重监测历史数据
     */
    @Override
    public List<TMiniHistory> selectTMiniHistoryList(SoMap params)
    {
        //根据选择的日期区间查询数据
        LambdaQueryWrapper<TMiniHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TMiniHistory::getUserId, params.getLong("userId"));
        wrapper.eq(TMiniHistory::getOpenid, params.getString("openId"));
        wrapper.ge(TMiniHistory::getDate, DateUtils.getDateBeforeDays(15));
        wrapper.le(TMiniHistory::getDate, DateUtils.getToday());
        wrapper.orderByAsc(TMiniHistory::getDate);
        return tMiniHistoryMapper.selectList(wrapper);
    }

    /**
     * 查询体重监测历史数据列表
     *
     * @param params 体重监测历史数据
     * @return 体重监测历史数据
     */
    @Override
    public List<TMiniHistory> selectHistoryMonth(SoMap params)
    {
        int year=params.getInt("year",DateUtils.getCurrentYear());
        int month=params.getInt("month",DateUtils.getCurrentMonth());
        //根据选择的日期区间查询数据
        LambdaQueryWrapper<TMiniHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TMiniHistory::getUserId, params.getLong("userId"));
        wrapper.eq(TMiniHistory::getOpenid, params.getString("openId"));
        wrapper.ge(TMiniHistory::getDate, params.get("startDate",DateUtils.getFirstDayOfMonth(year,month)));
        wrapper.le(TMiniHistory::getDate, params.get("endDate",DateUtils.getLastDayOfMonth(year,month)));
        wrapper.orderByAsc(TMiniHistory::getDate);
        return tMiniHistoryMapper.selectList(wrapper);
    }

    /**
     * 查询体重监测历史数据列表
     *
     * @param params 体重监测历史数据
     * @return 体重监测历史数据
     */
    @Override
    public List<TMiniHistory> selectHistoryData(SoMap params){
        int year=params.getInt("year",DateUtils.getCurrentYear());
        int month=params.getInt("month",DateUtils.getCurrentMonth());
        MiniAppUser miniAppUser=SecurityUtils.getLoginUser().getMiniAppUser();
        //根据选择的日期区间查询数据
        LambdaQueryWrapper<TMiniHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TMiniHistory::getUserId, miniAppUser.getId());
        wrapper.eq(TMiniHistory::getOpenid, miniAppUser.getOpenId());
        wrapper.ge(TMiniHistory::getDate, params.get("startDate",DateUtils.getFirstDayOfMonth(year,month)));
        wrapper.le(TMiniHistory::getDate, params.get("endDate",DateUtils.getLastDayOfMonth(year,month)));
        wrapper.orderByAsc(TMiniHistory::getDate);
        return tMiniHistoryMapper.selectList(wrapper);
    }

    /**
     * 用户历史数据分析
     *
     * @param params 体重监测历史数据
     * @return
     */
    @Override
    public Map historyAnalysis(SoMap params) {
        //统计用户历史打卡次数
        LambdaQueryWrapper<TMiniHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TMiniHistory::getUserId, params.getLong("userId"));
        wrapper.eq(TMiniHistory::getOpenid, params.getString("openId"));
        long recordCount= tMiniHistoryMapper.selectCount(wrapper);


        QueryWrapper<TMiniHistory> calcWrapper = new QueryWrapper<>();
        calcWrapper.eq("user_id", params.getLong("userId"));
        calcWrapper.eq("openid", params.getString("openId"));
        // 最大值
        Double maxWeight = baseMapper.selectObjs(calcWrapper.select("MAX(weight)"))
                .stream()
                .filter(obj -> obj != null)
                .map(obj -> new BigDecimal(obj.toString()).doubleValue())
                .findFirst()
                .orElse(null);

        // 最小值
        Double minWeight = baseMapper.selectObjs(calcWrapper.select("MIN(weight)"))
                .stream()
                .filter(obj -> obj != null)
                .map(obj -> new BigDecimal(obj.toString()).doubleValue())
                .findFirst()
                .orElse(null);

        // 平均值
        Double avgWeight = baseMapper.selectObjs(calcWrapper.select("AVG(weight)"))
                .stream()
                .filter(obj -> obj != null)
                .map(obj -> new BigDecimal(obj.toString()).doubleValue())
                .findFirst()
                .orElse(0.0);
        Map<String,Object> result=new HashMap<>();
        result.put("recordCount",recordCount);
        result.put("maxWeight",maxWeight);
        result.put("minWeight",minWeight);
        result.put("avgWeight",avgWeight);
        return result;
    }

    /**
     * 查询最近7天的体重监测历史数据
     *
     * @param params 体重监测历史数据
     * @return 结果
     */
    @Override
    public List<TMiniHistory> selectWeekHistoryData(SoMap params){
        MiniAppUser miniAppUser=SecurityUtils.getLoginUser().getMiniAppUser();
        //根据选择的日期区间查询数据
        LambdaQueryWrapper<TMiniHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TMiniHistory::getUserId, miniAppUser.getId());
        wrapper.eq(TMiniHistory::getOpenid, miniAppUser.getOpenId());
        wrapper.ge(TMiniHistory::getDate, params.get("start"));
        wrapper.le(TMiniHistory::getDate, params.get("end"));
        wrapper.orderByAsc(TMiniHistory::getDate);
        return tMiniHistoryMapper.selectList(wrapper);
    }

    /**
     * 新增体重监测历史数据
     *
     * @param tMiniHistory 体重监测历史数据
     * @return 结果
     */
    @Override
    public int insertTMiniHistory(TMiniHistory tMiniHistory)
    {
        tMiniHistory.setCreateTime(DateUtils.getNowDate());
        return tMiniHistoryMapper.insertTMiniHistory(tMiniHistory);
    }

    /**
     * 新增体重监测历史数据
     *
     * @param params 体重监测历史数据,来源于小程序日常打卡
     * @return 结果
     */
    @Override
    public int insertWeightRecord(SoMap params)
    {
        //获取当前登陆用户的id
        MiniAppUser miniAppUser=SecurityUtils.getLoginUser().getMiniAppUser();
        //miniAppUser= miniAppUserMapper.selectMiniAppUserById(miniAppUser.getId());
        TMiniHistory tMiniHistory=new TMiniHistory();
        tMiniHistory.setId(UUID.fastUUID().toString());
        tMiniHistory.setUserId(miniAppUser.getId());
        tMiniHistory.setOpenid(miniAppUser.getOpenId());
        tMiniHistory.setDate(DateUtils.parseDate(DateUtils.getDate()));
        tMiniHistory.setHeight(miniAppUser.getHeight());
        tMiniHistory.setWeight(BigDecimal.valueOf(params.getDouble("weight")));
        tMiniHistory.setBmi(params.getString("bmi","--"));
        tMiniHistory.setRemark(params.getString("remark",""));
        tMiniHistory.setCreateTime(DateUtils.getNowDate());
        return tMiniHistoryMapper.insert(tMiniHistory);
    }


    /**
     * 判断当日用户是否已经打卡
     *
     * @param params 参数
     * @return 若当日已打卡返回 true，否则返回 false
     */
    public boolean isUserAlreadyCheckedInToday(SoMap params) {
        //获取当前登陆用户的id
        MiniAppUser miniAppUser = SecurityUtils.getLoginUser().getMiniAppUser();


        // 构建查询条件，判断当天是否已有记录
        LambdaQueryWrapper<TMiniHistory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TMiniHistory::getUserId, miniAppUser.getId());
        wrapper.eq(TMiniHistory::getOpenid, miniAppUser.getOpenId());
        wrapper.eq(TMiniHistory::getDate, DateUtils.getToday());

        // 查询当天是否已有记录
        Long count = tMiniHistoryMapper.selectCount(wrapper);
        return count > 0;
    }

    /**
     * 修改体重监测历史数据
     *
     * @param tMiniHistory 体重监测历史数据
     * @return 结果
     */
    @Override
    public int updateTMiniHistory(TMiniHistory tMiniHistory)
    {
        tMiniHistory.setUpdateTime(DateUtils.getNowDate());
        return tMiniHistoryMapper.updateTMiniHistory(tMiniHistory);
    }

    /**
     * 批量删除体重监测历史数据
     *
     * @param ids 需要删除的体重监测历史数据主键
     * @return 结果
     */
    @Override
    public int deleteTMiniHistoryByIds(String[] ids)
    {
        return tMiniHistoryMapper.deleteTMiniHistoryByIds(ids);
    }

    /**
     * 删除体重监测历史数据信息
     *
     * @param id 体重监测历史数据主键
     * @return 结果
     */
    @Override
    public int deleteTMiniHistoryById(String id)
    {
        return tMiniHistoryMapper.deleteTMiniHistoryById(id);
    }
}

